<template>
  <div class="coupons-container">
    <div class="header">
      <h1>优惠券管理</h1>
      <button @click="addCoupon" class="btn btn-primary">
        <i class="material-icons">add</i>
        创建优惠券
      </button>
    </div>
    
    <div class="content">
      <div class="coupons-table">
        <table>
          <thead>
            <tr>
              <th>优惠券ID</th>
              <th>优惠金额</th>
              <th>最低消费</th>
              <th>有效期（天）</th>
              <th>已发放</th>
              <th>已使用</th>
              <th>状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="coupon in coupons" :key="coupon.couponId">
              <td>#{{ coupon.couponId }}</td>
              <td>¥{{ coupon.discountAmount }}</td>
              <td>¥{{ coupon.minimumAmount }}</td>
              <td>{{ coupon.validDays }}</td>
              <td>{{ coupon.issued }}</td>
              <td>{{ coupon.used }}</td>
              <td>
                <span :class="['status', coupon.status === 1 ? 'active' : 'inactive']">
                  {{ coupon.status === 1 ? '启用' : '禁用' }}
                </span>
              </td>
              <td class="actions">
                <button @click="editCoupon(coupon)" class="action-btn edit">编辑</button>
                <button @click="toggleCouponStatus(coupon)" class="action-btn toggle">
                  {{ coupon.status === 1 ? '禁用' : '启用' }}
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'Coupons',
  data() {
    return {
      showAddDialog: false,
      coupons: []
    }
  },
  mounted() {
    this.fetchCouponsList()
  },
  methods: {
    async fetchCouponsList() {
      try {
        // 从积分商店获取优惠券模板
        const response = await axios.post('http://localhost:8888/elm/PointsStoreController/list')
        if (response.data.code === 200 || response.data.code === '200') {
          // 过滤出优惠券类型的商品
          const allItems = response.data.result || []
          this.coupons = allItems.filter(item => 
            item.itemName && (item.itemName.includes('优惠券') || item.itemName.includes('折扣'))
          ).map(item => ({
            couponId: item.itemId,
            discountAmount: this.extractDiscountAmount(item.itemName, item.itemDescription),
            minimumAmount: this.extractMinimumAmount(item.itemDescription),
            validDays: 30, // 默认30天
            issued: Math.floor(Math.random() * 100), // 模拟数据
            used: Math.floor(Math.random() * 50), // 模拟数据
            status: item.status || 1,
            itemName: item.itemName,
            itemDescription: item.itemDescription,
            pointsRequired: item.pointsRequired
          }))
        }
      } catch (error) {
        console.error('获取优惠券列表失败:', error)
        this.coupons = []
      }
    },
    
    extractDiscountAmount(name, description) {
      // 从名称或描述中提取折扣金额
      const match = (name + ' ' + description).match(/(\d+)元/);
      return match ? parseInt(match[1]) : 5;
    },
    
    extractMinimumAmount(description) {
      // 从描述中提取最低消费金额
      const match = description.match(/满(\d+)/);
      return match ? parseInt(match[1]) : 0;
    },
    
    async editCoupon(coupon) {
      const newName = prompt('请输入新的优惠券名称:', coupon.itemName)
      const newDescription = prompt('请输入新的优惠券描述:', coupon.itemDescription)
      const newPoints = prompt('请输入所需积分:', coupon.pointsRequired)
      
      if (newName && newDescription && newPoints) {
        try {
          await axios.post('http://localhost:8888/elm/PointsStoreController/update', {
            itemId: coupon.couponId,
            itemName: newName,
            itemDescription: newDescription,
            pointsRequired: parseInt(newPoints),
            status: coupon.status
          })
          alert('优惠券更新成功')
          this.fetchCouponsList()
        } catch (error) {
          console.error('更新优惠券失败:', error)
          alert('更新失败')
        }
      }
    },
    
    async toggleCouponStatus(coupon) {
      try {
        const newStatus = coupon.status === 1 ? 0 : 1
        await axios.post('http://localhost:8888/elm/PointsStoreController/updateStatus', {
          itemId: coupon.couponId,
          status: newStatus
        })
        coupon.status = newStatus
        alert('优惠券状态已更新')
      } catch (error) {
        console.error('更新状态失败:', error)
        alert('状态更新失败')
      }
    },
    
    async addCoupon() {
      const name = prompt('请输入优惠券名称:')
      const description = prompt('请输入优惠券描述:')
      const points = prompt('请输入所需积分:')
      
      if (name && description && points) {
        try {
          await axios.post('http://localhost:8888/elm/PointsStoreController/add', {
            itemName: name,
            itemDescription: description,
            pointsRequired: parseInt(points),
            stock: 1000,
            status: 1
          })
          alert('优惠券创建成功')
          this.showAddDialog = false
          this.fetchCouponsList()
        } catch (error) {
          console.error('创建优惠券失败:', error)
          alert('创建失败')
        }
      }
    }
  }
}
</script>

<style scoped>
.coupons-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  background: white;
  padding: 20px 30px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.header h1 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: all 0.3s;
}

.btn-primary {
  background: linear-gradient(135deg, #FF6B6B 0%, #FF5252 100%);
  color: white;
}

.btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(255, 107, 107, 0.3);
}

.content {
  flex: 1;
  overflow-y: auto;
  padding: 30px;
}

.coupons-table {
  background: white;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

table {
  width: 100%;
  border-collapse: collapse;
}

thead {
  background-color: #f5f5f5;
}

th {
  padding: 15px;
  text-align: left;
  font-weight: 600;
  color: #333;
  border-bottom: 2px solid #eee;
}

td {
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.status {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
}

.status.active {
  background-color: #d4edda;
  color: #155724;
}

.status.inactive {
  background-color: #f8d7da;
  color: #721c24;
}

.actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.action-btn.edit {
  background-color: #e3f2fd;
  color: #1976d2;
}

.action-btn.edit:hover {
  background-color: #bbdefb;
}

.action-btn.toggle {
  background-color: #fff3e0;
  color: #f57c00;
}

.action-btn.toggle:hover {
  background-color: #ffe0b2;
}
</style>
